<!--
 * @Date: 2022-02-22 16:02:33
 * @Author: 陶子
 * @LastEditTime: 2023-06-27 19:13:38
 * @FilePath: \jk_one-stop_pc\src\views\workManagement\workOrder\buildWorkOrder.vue
 * @pageName: 这是--(新建工单表单)--页面
-->
<template>
  <jke-modal :visible.sync='jkeForm.visible' :width='1200' :title='jkeForm.title' :fullscreen.sync='jkeForm.fullscreen'
    :switchFullscreen='jkeForm.switchFullscreen'>
    <div class='form-body' :style="{ height: jkeForm.fullscreen ? 'calc(100vh - 112px)' : 'auto' }">
      <a-card title='基础信息' :bordered='false' style='margin-top: 12px'>
        <a-form-model ref='ruleFormOne' :model='buildForm' :rules='rulesList'>
          <a-row>
            <a-col :span='7'>
              <a-form-model-item label='工单编号' style='width: 100%'>
                <a-input v-model='buildForm.orderCode' placeholder='请输入，不输入则自动生成' />
              </a-form-model-item>
            </a-col>
            <a-col :span='1'></a-col>
            <a-col :span='7'>
              <a-form-model-item label='计划时间' style='width: 100%' prop='arrPlanTime'>
                <a-range-picker :show-time="{ format: 'HH:mm' }" style='width: 100%' v-model='buildForm.arrPlanTime'
                  format='YYYY-MM-DD HH:mm' :placeholder="['请输入', '请输入']" @change='startTimeChange' />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span='7'>
              <a-form-model-item label='关联订单' style='width: 100%'>
                <a-input @click='outopenIt' v-model='buildForm.saleCode' placeholder='请选择' :read-only='true'
                  :class="buildForm.saleCode ? 'has-value' : ''">
                  <a-icon slot='suffix' type='down' style='color: #cdcdcd; font-size: 12px' class='down-icon' />
                  <a-icon slot='suffix' type='close-circle' theme='filled' class='close-icon'
                    @click="getSaleSelectValue(false, '', [])" />
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span='1'></a-col>
            <a-col :span='7'>
              <a-form-model-item label='生产物品' style='width: 100%' prop='serialId'>
                <a-input @click='openIt' v-model='goodsName' placeholder='请选择' :read-only='true'
                  :class="goodsName ? 'has-value' : ''">
                  <a-icon slot='suffix' type='down' style='color: #cdcdcd; font-size: 12px' class='down-icon' />
                  <a-icon slot='suffix' type='close-circle' theme='filled' class='close-icon'
                    @click="getSelectValue(false, '', [])" />
                </a-input>
              </a-form-model-item>

            </a-col>
            <a-col :span='1'></a-col>
            <a-col :span='7'>
              <a-form-model-item label='计划生产数量' style='width: 100%' prop='planProduceNum'>
                <a-input v-model='buildForm.planProduceNum' @input='projectBudgetInput(buildForm.planProduceNum)'
                  @blur='blurNum(buildForm.planProduceNum)' placeholder='请输入' />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>
      <createFormItem ref='createFormItemRef' :formType='3' />

      <a-card title='生产任务' :bordered='false' style='margin-top: 12px; margin-bottom: 12px; flex: 1'>
        <a-col :span='24'>
          <div style='margin-bottom: 10px'>
            <a-button type='primary' icon='plus' style='width: auto; padding: 0 10px' @click='openItProcess'>按工序添加
            </a-button>
            <a-button type='primary' icon='plus' @click='openItCraft'
              style='margin-left: 10px; width: auto; padding: 0 10px'>按工艺添加
            </a-button>
            <a-button type='primary' icon='minus' @click='delselect'
              style='margin-left: 10px; width: auto; padding: 0 10px'>删除
            </a-button>
          </div>

          <a-form-model :colon='false' class='pathParamsForm' ref='pathParamsForm' :model='pathParams' :rules='rules'>
            <a-table rowKey='id' :scroll="{ x: true }" :row-selection="{
              selectedRowKeys: selectedRowKeys,
              columnWidth: 50,
              columnTitle: '',
              onChange: onSelectChange,
            }"
              :columns='pathParams.columns' :data-source='pathParams.dataSource' :customRow='customRow'
              :pagination='false'>

              <template slot='customSort' slot-scope='text, record, index'>
                <div style='cursor: pointer' class='draggable'>
                  <a-icon type='unordered-list' :style="{ fontSize: '24px' }" />
                </div>
              </template>

              <template slot='index' slot-scope='text, record, index'>
                <div>
                  {{ index + 1 }}
                </div>
              </template>

              <template :slot='el.title' v-for='el in customColumns'>
                <span style='color: red'>*</span><span style='font-weight: bold'> {{ el.fieldName }}</span>
              </template>

              <template slot='processWorkUnit' slot-scope='text, record, index'>
                <a-form-model-item :prop="'dataSource.' + index + '.processWorkUnit'" :rules='rules.processWorkUnit'>
                  <a-range-picker v-model='record.processWorkUnit' :show-time="{ format: 'YYY-MM-DD HH:mm' }"
                    style='width: 100%' format='YYYY-MM-DD HH:mm' :placeholder="['请选择', '请选择']" />
                </a-form-model-item>
              </template>

              <div slot="customProcessesName"><span style="color: #f25643">* </span><span style="font-weight: bold;">工序</span></div>
              <div slot="processWorkUnitName"><span style="color: #f25643">* </span><span style="font-weight: bold;">任务时间</span></div>
              <div slot="processWorkRateName"><span style="color: #f25643">* </span><span style="font-weight: bold;">计划数</span></div>

              <div v-for="item in columnsdata" :slot="item.fieldName"><span style="color: #f25643" v-show="item.fieldMust === 2">* </span><span style="font-weight: bold;">{{ item.fieldName }}</span></div>

              <template slot='processWorkRate' slot-scope='text, record, index'>
                <a-form-model-item :prop="'dataSource.' + index + '.processWorkRate'" :rules='rules.processWorkUnit'>
                  <a-input @input='processWorkRateInput(record.processWorkRate, record)'
                    v-model='record.processWorkRate' placeholder='请输入' />
                </a-form-model-item>
              </template>

              <template slot='pieceRate' slot-scope='text, record, index'>
                <a-form-model-item :prop="'dataSource.' + index + '.pieceRate'" :rules='rules.pieceRate'>
                  <a-input-number style="width: 100%;" :step="0.0001" precision="4" v-model='record.pieceRate'
                    placeholder='请输入' />
                </a-form-model-item>
              </template>

              <template :slot='el.name' slot-scope='text, record, index' v-for='el in columnsdata'>
                <a-form-model-item :prop="'dataSource.' + index + `.${el.name}`" :rules='rules[el.name]'>
                  <a-input @input='exJson($event, el, index)' style='width: 100%' v-model='record[el.name]'
                    :disabled='el.fieldMust == 1' v-if='el.type == 1' placeholder='请输入' />

                  <a-textarea @input='exJson($event, el, index)' style='width: 100%' v-model='record[el.name]'
                    :disabled='el.fieldMust == 1' v-else-if='el.type == 2' autosize></a-textarea>

                  <a-input-number @change='exJson($event, el, index)' style='width: 100%' v-model='record[el.name]'
                    :max='getMaxValueForDigits(el.fieldLength * 1)' :min='0' :disabled='el.fieldMust == 1'
                    v-else-if='el.type == 3' />

                  <a-input-number v-if="el.fieldType == 4" :step="0.0001" style="width: 100%"
                    :disabled="el.fieldMust == 1" :placeholder="el.placeholder" :min="0.0001"
                    :max="getMaxValueForDigits1(el.fieldLength * 1)" v-model='record[el.name]'
                    :formatter="(value) => onInput(value, el)" @change='exJson($event, el, index)' />
                </a-form-model-item>
              </template>
            </a-table>
          </a-form-model>
        </a-col>
      </a-card>
    </div>
    <div class='footer-submit' :class="jkeForm.fullscreen ? 'form-footer' : ''">
      <a-button @click='goBack' class='submitBtn' style='margin-right: 10px'> 取消</a-button>
      <a-button @click='submitForm' type='primary' :loading='subLoading' class='submitBtn'> 提交</a-button>
    </div>
    <!-- 销售订单 -->
    <goodsTableSelect ref='SaleSelect' @getSelectValue='getSaleSelectValue' :key='Selectindex'></goodsTableSelect>
    <!-- 产品 -->
    <goodsTableSelect ref='tableSelect' @getSelectValue='getSelectValue' :key='indexdeta'></goodsTableSelect>
    <!-- 流程 -->
    <tableSelect ref='tableSelectCircuit' @getSelectValue='getSelectValueCircuit' :key='indexCircuit'>
      <div slot='head'>
        <div class='uni-card' style='background: #fff'>
          <a-form-model ref='ruleForm' layout='inline' :model='filterFormCircuit'>
            <a-form-model-item label='流程编号'>
              <a-input v-model='filterFormCircuit.flowCode' placeholder='请输入' />
            </a-form-model-item>
            <a-form-model-item label='流程名称'>
              <a-input v-model='filterFormCircuit.flowName' placeholder='请输入' />
            </a-form-model-item>
            <a-form-model-item>
              <a-button @click='searchCircuit()' type='primary'> 搜索</a-button>
              <a-button style='margin-left: 10px' @click='searchResetCircuit'>重置</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </tableSelect>
    <tableSelect ref='tableSelectProcess' @getSelectValue='getSelectValueProcess' :key='indexProcess'>
    </tableSelect>
    <tableSelect ref='tableSelectCraft' @getSelectValue='getSelectValueCraft' :key='indexCraft'>
    </tableSelect>
  </jke-modal>
</template>

<script>
import moment from 'moment'
import { mapState } from 'vuex'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { clearNoNum, validateDuplicateValue } from '@/utils/util'
import { API } from '@/api/requestFzs'
import { BasicqueryById, carfadd, queryEditForm, cardedit, detailTableForm, Qtdl } from '@/api/productOrder'
import { outopenItcolumns } from './allColumn'
import { queryFlowProcessListByFlowId } from '@/api/goodsManagement'
import { getAction } from '@/api/manage'
import crumbs from '@/components/crumbs.vue'
import tableSelect from '@/components/tableSelect'
import goodsTableSelect from '@/components/goodsTableSelect'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import createFormItem from '@/components/createForm.vue'
import { APILX } from '@/api/requestLx'

export default {
  data() {
    return {
      jkeForm: {
        title: '新建工单',
        visible: false,
        fullscreen: true,
        switchFullscreen: true
      },
      indexdeta: 2,
      //下拉改弹窗
      index: 0,
      Selectindex: 0,
      edit: false,
      selectedRowKeys: [],
      selectedRows: [],
      columns: [
        {
          title: '物品编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'serialNumber',
          // searchIndex: 'serialNumber',
          searchKey: 'serialNumber',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'serialNumber'
          }
        },
        {
          title: '物品名称',
          width: 180,
          ellipsis: true,
          dataIndex: 'serialName',
          searchIndex: 'serialName',
          searchKey: 'serialName',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'serialName'
          }
        },
        {
          title: '规格',
          width: 100,
          ellipsis: true,
          searchIndex: 'serialSpecifications',
          dataIndex: 'serialSpecifications',
          searchKey: 'serialSpecifications',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'serialSpecifications'
          }
        },
        {
          title: '物品属性',
          dataIndex: 'serialProperties',
          ellipsis: true,
          // fixed: 'left',
          width: 180,
          multi: 'multiple',
          searchIndex: 'serialProperties',
          options: [
            { label: '自制', key: '0' },
            { label: '外购', key: '1' }
          ],
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'dateIcon',
            customRender: 'serialProperties'
          }
        },
        {
          title: '单位',
          dataIndex: 'unitName',
          ellipsis: true,
          // fixed: 'left',
          width: 180,
          searchIndex: 'unitName',
          options: [],
          scopedSlots: {
            // filterDropdown: 'searchDropdown',
            // filterIcon: 'searchIcon',
            customRender: 'unitName'
          }
        },
        {
          title: '工艺路线',
          dataIndex: 'processRouteName',
          ellipsis: true,
          // fixed: 'left',
          width: 180,
          searchIndex: 'processRouteName',
          options: [],
          scopedSlots: {
            filterDropdown: 'searchDropdown',
            filterIcon: 'searchIcon',
            customRender: 'processRouteName'
          }
        },
        {
          title: '最小库存',
          dataIndex: 'inventoryMin',
          ellipsis: true,
          // fixed: 'left',
          width: 180,
          searchIndex: 'inventoryMin',
          options: [],
          scopedSlots: {
            // filterDropdown: 'searchDropdown',
            // filterIcon: 'searchIcon',
            // customRender: 'inventoryMin',
          }
        },
        {
          title: '最大库存',
          dataIndex: 'inventoryMax',
          ellipsis: true,
          // fixed: 'left',
          width: 180,
          searchIndex: 'inventoryMax',
          options: [],
          scopedSlots: {}
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          ellipsis: true,
          width: 180,
          searchIndex: 'createTime',
          sorter: true,
          scopedSlots: {
            // filterDropdown: 'selectDropdown',
            // filterIcon: 'dateIcon',
            // customRender: 'createTime',
          }
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          ellipsis: true,
          width: 180,
          searchIndex: 'updateTime',
          sorter: true,
          scopedSlots: {
            // filterDropdown: 'selectDropdown',
            // filterIcon: 'dateIcon',
            // customRender: 'createTime',
          }
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          ellipsis: true,
          width: 180,
          searchIndex: 'createBy',
          scopedSlots: {
            filterDropdown: 'createBy',
            filterIcon: 'dateIcon',
            customRender: 'createByName'
          }
        },
        {
          title: '更新人',
          dataIndex: 'updateBy',
          ellipsis: true,
          width: 180,
          searchIndex: 'updateBy',
          scopedSlots: {
            filterDropdown: 'updateBy',
            filterIcon: 'dateIcon',
            customRender: 'updateByName'
          }
        }
        // {
        //   title: '物品类型',
        //   width: 100,
        //   ellipsis: true,
        //   dataIndex: 'typeText',
        //   searchKey: 'type',
        //   type: 'select',
        //   scopedSlots: {
        //     filterDropdown: 'selectDropdown',
        //     filterIcon: 'selectIcon',
        //     customRender: 'typeText',
        //   },
        // },
        // {
        //   title: '物品分类',
        //   width: 100,
        //   ellipsis: true,
        //   dataIndex: 'categoryText',
        //   searchKey: 'category',
        //   type: 'tree',
        //   scopedSlots: {
        //     filterDropdown: 'selectDropdown',
        //     filterIcon: 'selectIcon',
        //     customRender: 'categoryText',
        //   },
        // },
      ],
      outopenItcolumns: outopenItcolumns,
      goodsValue: '',
      goodsText: '',
      filterForm: {
        goodsCode: '', //物品编号
        goodsName: '' //物品名称
      },
      //下拉改弹窗结束
      principalStr: '',
      subLoading: false,
      goodsName: '',
      SelectRowChange: [],
      serialName: '',
      serialNumber: '',
      serialSpecifications: '',
      showTable: false,
      buildForm: {
        arrPlanTime: '',
        orderCode: '',
        planStartTime: '',
        planEndTime: '',
        planProduceNum: '',
        saleOrderId: '',
        serialId: '',
        saleCode: '',
        produceOrderTaskDtoList: []
      },
      rulesList: {
        arrPlanTime: [{ required: true, message: '请选择', trigger: 'change' }],
        serialId: [{ required: true, message: '请选择', trigger: 'blur,change' }],
        planProduceNum: [{ required: true, message: '请输入', trigger: 'blur' }],
        orderCode: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      good_pageNo: 1,
      good_pageSize: 10,
      timeout: null,
      inputValue: '',
      craftList: [],
      craft_pageNo: 1,
      craft_pageSize: 10,
      timer: null,
      craftValue: '',
      rules: {
        processWorkUnit: [{ required: true, message: '请输入', trigger: ['change', 'blur'] }],
        processWorkRate: [{ required: true, message: '请输入', trigger: ['change', 'blur'] }],
        pieceRate: [{ required: true, message: '请输入', trigger: ['change', 'blur'] }]
      },
      customColumns: [], // 自定义的列
      // 工艺路线
      pathParams: {
        loading: false,
        dataSource: [],

        columns: [
          {
            title: '',
            dataIndex: 'customSort',
            width: 80,
            scopedSlots: { customRender: 'customSort' }
          },
          {
            title: '序号',
            dataIndex: 'index',
            width: 60,
            key: 'index',
            scopedSlots: { customRender: 'index' }
          },
          {
            dataIndex: 'processesName',
            key: 'processesName',
            // title: '工序',
            type: FormTypes.normal,
            slots: { title: 'customProcessesName' },
            scopedSlots: { customRender: 'processesName' },
            required: true
          },
          {
            dataIndex: 'processWorkUnit',
            key: 'processWorkUnit',
            // title: '任务时间',
            width: 320,
            type: FormTypes.slot,
            slots: { title: 'processWorkUnit' },
            scopedSlots: { customRender: 'processWorkUnit' }
          },
          {
            dataIndex: 'processWorkRate',
            key: 'processWorkRate',
            title: '计划数',
            type: FormTypes.inputNumber,
            slots: { title: 'processWorkRateName' },
            scopedSlots: { customRender: 'processWorkRate' }
          },
          {
            dataIndex: 'pieceRate',
            key: 'pieceRate',
            title: '计件单价',
            width: 240,
            type: FormTypes.inputNumber,
            scopedSlots: { customRender: 'pieceRate' }
          }
        ]
      },
      sortedData: [], // 排序后的数据
      sourceObj: {},
      targetObj: {},
      //分割线
      submitApi: null,
      attachment: '', //附件
      // 工序弹窗配置-----begin
      indexProcess: 0.2,
      processRowId: '',
      columnsProcess: [
        {
          title: '工序编号',
          dataIndex: 'processesCode',
          width: 180,
          ellipsis: true,
          searchIndex: 'processesCode',
          scopedSlots: {
            filterDropdown: 'searchDropdown',
            filterIcon: 'searchIcon',
            customRender: 'processesCode'
          }
        },
        {
          title: '工序名称',
          dataIndex: 'processesName',
          key: 'processesName',
          width: 180,
          ellipsis: true,
          searchIndex: 'processesName',
          scopedSlots: {
            filterDropdown: 'searchDropdown',
            filterIcon: 'searchIcon',
            customRender: 'processesName'
          }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          ellipsis: true,
          width: 180,
          searchIndex: 'createTime',
          sorter: true,
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          ellipsis: true,
          width: 180,
          searchIndex: 'updateTime',
          sorter: true,
          scopedSlots: { customRender: 'updateTime' }
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          ellipsis: true,
          width: 180,
          searchIndex: 'createBy',
          options: [],
          searchIndex: 'createBy',
          scopedSlots: {
            filterDropdown: 'selectPeople1',
            filterIcon: 'dateIcon'
            // customRender: 'createByName',
          }
        },
        {
          title: '更新人',
          dataIndex: 'updateBy',
          ellipsis: true,
          width: 180,
          searchIndex: 'updateBy',
          options: [],
          searchIndex: 'updateBy',
          scopedSlots: {
            filterDropdown: 'selectPeople2',
            filterIcon: 'dateIcon'
            // customRender: 'createByName',
          }
        }
      ],
      columnsdata: [],
      formTypeExtendedFields: [],
      processValue: '',
      processText: '',
      filterFormProcess: {
        processCode: '', //工序编号
        processName: '' //工序名称
      },
      // 工序弹窗配置-----end
      // -----流程弹窗配置-begin-----
      indexCircuit: 0.3,

      columnsCircuit: [
        {
          title: '流程编号',
          dataIndex: 'flowCode',
          key: 'flowCode',
          width: 180,
          ellipsis: true
        },
        {
          title: '流程名称',
          dataIndex: 'flowName',
          key: 'flowName',
          width: 180,
          ellipsis: true
        },
        {
          title: '组成工序',
          dataIndex: 'process',
          width: 180,
          key: 'process',
          ellipsis: true
        }
      ],
      circuitValue: '',
      circuitText: '',
      filterFormCircuit: {
        flowCode: '',
        flowName: ''
      },
      // -----流程弹窗配置-end-----
      // -----工艺弹窗配置-begin-----
      indexCraft: 0.4,
      columnsCraft: [
        {
          title: '工艺编号',
          dataIndex: 'processRouteCode',
          width: 180,
          key: 'processRouteCode',
          ellipsis: true,
          searchIndex: 'processRouteCode',
          scopedSlots: {
            filterDropdown: 'searchDropdown',
            filterIcon: 'searchIcon',
            customRender: 'processRouteCode'
          }
        },
        {
          title: '工艺名称',
          dataIndex: 'processRouteName',
          key: 'processRouteName',
          width: 180,
          ellipsis: true,
          searchIndex: 'processRouteName',
          scopedSlots: {
            filterDropdown: 'searchDropdown',
            filterIcon: 'searchIcon',
            customRender: 'processRouteName'
          }
        },
        {
          title: '工序',
          dataIndex: 'processesName',
          key: 'processesName',
          width: 180,
          ellipsis: true
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          ellipsis: true,
          width: 180,
          searchIndex: 'createTime',
          sorter: true,
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          ellipsis: true,
          width: 180,
          searchIndex: 'updateTime',
          sorter: true,
          scopedSlots: { customRender: 'updateTime' }
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          ellipsis: true,
          width: 180,
          searchIndex: 'createBy',
          options: [],
          searchIndex: 'createBy',
          scopedSlots: {
            filterDropdown: 'selectPeople1',
            filterIcon: 'dateIcon'
            // customRender: 'createByName',
          }
        },
        {
          title: '更新人',
          dataIndex: 'updateBy',
          ellipsis: true,
          width: 180,
          searchIndex: 'updateBy',
          options: [],
          searchIndex: 'updateBy',
          scopedSlots: {
            filterDropdown: 'selectPeople2',
            filterIcon: 'dateIcon'
            // customRender: 'createByName',
          }
        }
      ],
      craftValue: '',
      craftText: '',
      filterFormCraft: {
        craftCode: '',
        craftName: ''
      },
      // -----工艺弹窗配置-end-----
      // -----计划投料弹窗配置-begin-----
      indexInventory: 0.5,
      inventoryValue: '',
      inventoryText: '',
      filterFormInventory: {
        goodsCode: '',
        goodsName: ''
      },
      propsInventory: '',
      // -----计划投料弹窗配置-end-----
      contractList: [] // 关联订单下拉列表
    }
  },
  components: {
    FileUpload,
    crumbs,
    tableSelect,
    goodsTableSelect,
    createFormItem
  },
  computed: {
    ...mapState({
      collapsed: (state) => state.user.collapsed
    })
  },
  methods: {
    onInput(event) {
      let value = event + ''
      // 截断小数点后超过4位的部分
      if (value.includes('.')) {
        let parts = value.split('.')
        if (parts[1].length > 4) {
          value = parts[0] + '.' + parts[1].substring(0, 4)
        }
      } else {
        value = event
      }
      return value
    },
    getMaxValueForDigits1(digitCount) {
      if (digitCount <= 0) {
        throw new Error('Digit count must be a positive integer.')
      }
      return (Math.pow(10, digitCount) - 1) + 0.9999
    },
    customRow(record, index) {
      console.log('customRow', record, index)
      return {
        domProps: {
          draggable: true
        },
        style: {
          cursor: 'move'
        },
        on: {
          // 鼠标移入
          mouseenter: (event) => {
            var ev = event || window.event // 兼容IE
            ev.target.draggable = true
          },
          // 开始拖拽
          dragstart: (event) => {
            var ev = event || window.event
            ev.stopPropagation() // 阻止冒泡
            this.sourceObj = record // 得到源目标数据序号
            console.log('sourceCode', this.sourceObj)
          },
          // 拖动元素经过的元素
          dragover: (event) => {
            var ev = event || window.event
            ev.preventDefault()
          },
          // 鼠标松开
          drop: (event) => {
            var ev = event || window.event
            ev.stopPropagation()
            this.targetObj = record // 得到目标数据
            //获取想要换位置的两个下标
            let sourceindex = ''
            let targetindex = ''
            this.pathParams.dataSource.map((item, index) => {
              if (this.sourceObj.id == item.id) {
                sourceindex = index
              }
              if (this.targetObj.id == item.id) {
                targetindex = index
              }
            })
            // 这里就是让数据位置互换，让视图更新 你们可以看record，index的输出，看是什么
            let arr = []
            this.pathParams.dataSource.map((item, index) => {
              if (sourceindex == index) {
                arr.push(this.targetObj)
              } else if (targetindex == index) {
                arr.push(this.sourceObj)
              } else {
                arr.push(item)
              }
            })
            this.pathParams.dataSource = arr
          }
        }
      }
    },
    handleDragEnd(event) {
      const draggedItem = this.sortedData.splice(event.oldIndex, 1)[0]
      this.sortedData.splice(event.newIndex, 0, draggedItem)
      // 更新表格渲染
    },
    exJson(e, field) {
      this.pathParams.dataSource = JSON.parse(JSON.stringify(this.pathParams.dataSource))
      console.log(field.name, 'field', this.$refs.pathParamsForm)
      this.$refs.pathParamsForm.validate()

      this.$forceUpdate()
    },
    async rester() {
      this.pathParams.dataSource = []
      this.pathParams.columns = [
        {
          dataIndex: 'customSort',
          width: 80,
          scopedSlots: { customRender: 'customSort' }
        },
        {
          // title: '序号',
          dataIndex: 'index',
          width: 60,
          key: 'index',
          scopedSlots: { customRender: 'index' }
        },
        {
          dataIndex: 'processesName',
          key: 'processesName',
          // title: '工序',
          width: 120,
          type: FormTypes.normal,
          scopedSlots: { customRender: 'processesName' },
          slots: { title: 'customProcessesName' }
        },
        {
          dataIndex: 'processWorkUnit',
          key: 'processWorkUnit',
          // title: '任务时间',
          width: 320,
          type: FormTypes.slot,
          slots: { title: 'processWorkUnitName' },
          scopedSlots: { customRender: 'processWorkUnit' }
        },
        {
          dataIndex: 'processWorkRate',
          key: 'processWorkRate',
          // title: '计划数',
          width: 320,
          type: FormTypes.inputNumber,
          slots: { title: 'processWorkRateName' },
          scopedSlots: { customRender: 'processWorkRate' }
        },
        {
          dataIndex: 'pieceRate',
          key: 'pieceRate',
          title: '计件单价',
          width: 240,
          type: FormTypes.inputNumber,
          scopedSlots: { customRender: 'pieceRate' }
        }
      ]
      let res = await APILX.formTypeExtendedFieldList({ formType: 2 })
      if (res.code == 200 && res.result) {
        let formTypeExtendedFields = res.result
        let columns = []
        formTypeExtendedFields.forEach((fields) => {
          let tableHead = {
            title: fields.fieldName,
            dataIndex: 'extDataJson.' + fields.fieldKey,
            ellipsis: true,
            width: 150,
            searchIndex: 'extDataJson.' + fields.fieldKey,
            scopedSlots: {
              filterDropdown: 'searchDropdown',
              filterIcon: 'searchIcon'
            }
          }
          columns.push(tableHead)
        })
        this.outopenItcolumns = [...this.outopenItcolumns, ...columns]
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleSelectRowChange(row) {
      this.SelectRowChange = row
    },
    delselect() {
      let that = this
      if (!that.selectedRowKeys.length > 0) {
        this.$antdMessage.warning('请先选择数据')
        return
      }
      that.$antdConfirm({
        title: this.edit ? '确认删除工序？' : '确认删除工序吗？',
        content: this.edit ? `操作将同时删除关联的报工，删除后不可恢复！` : '删除后不可恢复！',
        onOk() {
          let list = that.resArr(that.pathParams.dataSource, that.selectedRowKeys)
          that.pathParams.dataSource = list
          that.selectedRowKeys = []
          that.selectedRows = []
        },
      })
    },
    resArr(arr1, arr2) {
      return arr1.filter((v) => arr2.every((val) => val != v.id))
    },
    getMaxValueForDigits(digitCount) {
      if (digitCount <= 0) {
        throw new Error('Digit count must be a positive integer.')
      }
      return Math.pow(10, digitCount) - 1
    },
    initForm(record) {
      this.rester()
      if (record && record.id) {
        this.edit = true
        this.jkeForm.visible = true
        this.jkeForm.title = '编辑工单'
        this.FormDetail(record)
      } else {
        this.jkeForm.title = '新建工单'
        this.jkeForm.visible = true
        this.buildForm.id = ''
        let currentTime = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace('T', ' ')
        let timeStart = currentTime.substr(0, currentTime.length - 3)
        let timeEnd = currentTime.substr(0, currentTime.length - 8) + '23:59'
        this.buildForm.arrPlanTime = [moment(timeStart, 'YYYY-MM-DD HH:mm:ss'), moment(timeEnd, 'YYYY-MM-DD HH:mm:ss')]
        this.buildForm.planStartTime = timeStart
        this.buildForm.planEndTime = timeEnd
        this.buildForm.orderCode = ''
        this.buildForm.planProduceNum = ''
        this.buildForm.saleOrderId = ''
        this.buildForm.saleCode = ''
        this.buildForm.serialId = ''
        this.buildForm.produceOrderTaskDtoList = ''
        this.goodsName = ''
        this.pathParams.dataSource = []
        APILX.formTypeExtendedFieldList({ formType: 7 })
          .then((res) => {
            console.log(res, 'res')
            if (res.code == 200 && res.result) {
              let formTypeExtendedFields = res.result || []
              this.formTypeExtendedFields = formTypeExtendedFields
              let column = []
              let data = []
              formTypeExtendedFields.forEach((field) => {
                this.rules[field.fieldKey] = [
                  {
                    required: field.fieldMust === 2,
                    message: '请输入',
                    trigger: ['change', 'blur']
                  }
                ]
                data.push({
                  name: field.fieldKey,
                  type: field.fieldType,
                  fieldMust: field.fieldMust,
                  ...field
                })
                column.push({
                  // title: field.fieldName,
                  dataIndex: +field.fieldKey,
                  isrequired: true,
                  type: field.fieldType,
                  width: 350,
                  ellipsis: true,
                  scopedSlots: { customRender: field.fieldKey },
                  slots: { title: field.fieldName }
                })

                this.customColumns = [].push({
                  title: field.fieldName,
                  dataIndex: +field.fieldKey,
                  type: field.fieldType,
                  width: 350,
                  ellipsis: true,
                  scopedSlots: { customRender: field.fieldKey },
                  slots: { title: field.fieldName }
                })
              })

              this.pathParams.columns = this.pathParams.columns.concat(column)
              this.columnsdata = data
            }
          })
          .finally(() => {
          })
      }
    },
    FormDetail(record) {
      detailTableForm({ id: record.id }).then((res) => {
        if (res.code == 200) {
          let formTypeExtendedFields = res.basicDynamicFieldConfig || []
          this.formTypeExtendedFields = formTypeExtendedFields
          let column = []
          let data = []
          formTypeExtendedFields.forEach((field) => {
            this.rules[field.fieldKey] = [{ required: field.fieldMust === 2, message: '请输入', trigger: ['change', 'blur'] }]
            data.push({
              name: field.fieldKey,
              type: field.fieldType,
              fieldMust: field.fieldMust,
              ...field
            })
            column.push({
              title: field.fieldName,
              dataIndex: +field.fieldKey,
              isrequired: true,
              type: field.fieldType,
              width: 200,

              scopedSlots: { customRender: field.fieldKey }
            })
          })

          this.pathParams.columns = this.pathParams.columns.concat(column)
          this.columnsdata = data
          this.pathParams.dataSource = res.result.map((e) => {
            e.processWorkUnit = [
              moment(e.planStartTime).format('YYYY-MM-DD HH:mm:ss'),
              moment(e.planEndTime).format('YYYY-MM-DD HH:mm:ss')
            ]

            e.processWorkRate = e.planProduceNum
            return e
          })
          this.listdata = []
          formTypeExtendedFields.forEach((item) => {
            this.pathParams.dataSource.forEach((el, index) => {
              for (let key in el.extDataJson) {
                if (item.fieldKey === key) {
                  this.$set(this.pathParams.dataSource[index], item.fieldKey, el.extDataJson[key])
                }
              }
            })
          })
        }
      })
      queryEditForm({ id: record.id }).then((res) => {
        if (res.code == 200) {
          this.buildForm = res.result
          this.buildForm.serialId = res.result.serialId
          this.buildForm.planStartTime = res.result.planStartTime
          this.buildForm.planEndTime = res.result.planEndTime
          this.buildForm.saleOrderId = res.result.saleOrderId
          this.buildForm.saleCode = res.result.sellOrderCode
          let monet = res.result.timePeriod.split('~')
          this.buildForm.arrPlanTime = [
            moment(monet[0], 'YYYY-MM-DD HH:mm:ss'),
            moment(monet[1], 'YYYY-MM-DD HH:mm:ss')
          ]
          this.goodsName = `${res.result.serialNumber || '-'}-${res.result.serialName || '-'} - ${res.result.serialSpecifications || '-'
            }`
          if (record.copy) {
            this.buildForm.id = ''
            this.buildForm.orderCode = ''
            this.jkeForm.title = '新建工单'
          }
          setTimeout(() => {
            this.$refs.createFormItemRef.setFields({
              ...this.buildForm,
              inWarehouseTimeText: this.buildForm.inWarehouseTime
            })
          }, 100)
        } else {
          this.$antdMessage.error(res.message)
        }
      })
      this.$forceUpdate()
    },
    selectDate(val, p) {
      console.log(val, p)
    },
    openItCircuit() {
      this.filterFormCircuit = {
        flowCode: '',
        flowName: ''
      }
      let goods = this.buildForm.goodsId
      if (!goods) {
        this.$antdMessage.info('请先选择产品')
        return
      }
      let par = {
        list: `/prodset/messProductFlow/queryFlowListByGoodsId?goodsId=${this.goodsValue}`,
        visible: true, //弹窗开启
        title: '工序', //标题名称
        multi: false, //是否多选
        columns: this.columnsCircuit, //表格配置
        value: this.circuitValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.circuitText, //回显的中文，如：'张三'
        textKey: 'processName' //回显的中文key
      }
      this.$refs.tableSelectCircuit.getInit(par)
    },
    getSelectValueCircuit(id, text, item) {
      if (!id) {
        return
      }
      this.indexCircuit += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.circuitValue = id
      this.circuitText = text
      this.buildForm.craftId = id
      this.buildForm.craftId = ''
      this.buildForm.craftSource = 'new'
      queryFlowProcessListByFlowId({ flowId: id }).then((res) => {
        if (res.result) {
          let newData = res.result.records || []
          this.$refs.craftPath.initialize()
          newData = newData.map((carft) => {
            carft.planStartTime = this.buildForm.planStartTime
            carft.planEndTime = this.buildForm.planEndTime
            return carft
          })
          this.pathParams.dataSource = newData
          this.buildForm.craftSource = 'process'
        }
      })
    },
    searchResetCircuit() {
      this.filterFormCircuit.flowCode = ''
      this.filterFormCircuit.flowName = ''
      this.$refs.tableSelectCircuit.searchReset()
    },
    searchCircuit() {
      this.$refs.tableSelectCircuit.searchQuery(this.filterFormCircuit)
    },
    // -----选择流程事件-end-----
    // -----选择工艺事件-begin-----
    valueChange() {
      let value = this.$refs.craftPath.getValuesSync({ validate: true })
    },

    openItCraft() {
      let par = {
        list: `/basicprocess/basicProcessRouteInfo/list`,
        visible: true, //弹窗开启
        title: '工序', //标题名称
        multi: false, //是否多选
        columns: this.columnsCraft, //表格配置
        value: this.craftValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.craftText, //回显的中文，如：'张三'
        textKey: 'craftName' //回显的中文key
      }
      this.$refs.tableSelectCraft.getInit(par)
    },
    getSelectValueCraft(id, text, item) {
      console.log(id, text, item, '列表选择的数据')
      if (!id) {
        return
      }
      this.indexCraft += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.craftValue = id
      this.craftText = text

      this.craftChange(id)
    },
    searchResetCraft() {
      this.filterFormCraft.processRouteCode = ''
      this.filterFormCraft.processRouteName = ''
      this.$refs.tableSelectCraft.searchReset()
      this.$forceUpdate()
    },
    searchCraft() {
      this.$refs.tableSelectCraft.queryParam = this.filterFormCraft
      this.$refs.tableSelectCraft.searchQuery(this.filterFormCraft)
    },
    // -----选择工艺事件-end-----
    handleDelete(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
    },
    // 工序弹窗事件-----begin
    openItProcess(props) {
      let values = ''
      console.log(this.pathParams.dataSource, 'this.pathParams.dataSource')
      if (this.pathParams.dataSource.length) {
        values = this.pathParams.dataSource.map(item => item.processesId).join()
      }
      let par = {
        list: '/basic/basicProductionProcesses/list',
        visible: true, //弹窗开启
        title: '工序', //标题名称
        multi: true, //是否多选
        columns: this.columnsProcess, //表格配置
        value: values, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.processText, //回显的中文，如：'张三'
        textKey: 'processName', //回显的中文key
        action: 'post'
      }
      this.$refs.tableSelectProcess.getInit(par)
    },
    getSelectValueProcess(id, text, items, rowId) {
      let item = JSON.parse(JSON.stringify(items))
      let newAry = []
      if (item.length > 0) {
        // 查找是否有重复数据之外的数据，有的话，就把剩余数据添加到table中
        newAry = item.filter((e) => {
          let flag = true
          for (let i = 0; i < this.pathParams.dataSource.length; i++) {
            if (this.pathParams.dataSource[i].processesId == e.id) {
              flag = false
            }
          }
          return flag
        })
      }
      this.indexProcess += 1

      this.formTypeExtendedFields.forEach((li, i) => {
        items.forEach((el, index) => {
          items[index][li.fieldKey] = ''
        })
      })

      console.log(items, 'items')
      let newData = newAry.map((e) => {
        if (e.extDataJson) {
          for (let key in e.extDataJson) {
            e[key] = e.extDataJson[key]
            this.$set(e, key, e.extDataJson[key])
          }
        }
        e.processesId = e.id
        this.$set(e, 'processWorkUnit', this.buildForm.arrPlanTime)
        this.$set(e, 'processWorkRate', this.buildForm.planProduceNum)
        return e
      })

      this.pathParams.dataSource = this.pathParams.dataSource.concat(newData)
    },
    onChangeSelect(obj) {
      let tableValue = this.$refs.craftPath.getValuesSync({ validate: false }).values
      for (let i = 0; i < tableValue.length; i++) {
        const v = tableValue[i]
        if (v.processId == this.processValue) {
          if (v.id == this.processRowId) {
            return
          }
          this.$refs.craftPath.removeRows(this.processRowId)
          this.$antdMessage.warning('该工序已存在，请直接修改数据')
          return
        }
      }
      this.$refs.craftPath.setValues([
        {
          rowKey: this.processRowId, // 行的id
          values: {
            // 在这里 values 中的 specifications 是你 columns 中配置的 key
            processId: this.processValue,
            processShowName: `${obj.processCode}-${obj.processName} `,
            processWorkUnit: obj.processWorkUnit || '',
            processRequire: obj.processRequire || '',
            processName: obj.processName || '',
            processWorkRate: obj.processWorkRate || '',
            qualityTestProcess: obj.qualityTestProcess
          }
        }
      ])
    },
    searchResetProcess() {
      this.filterFormProcess.processesCode = ''
      this.filterFormProcess.processesName = ''
      this.$refs.tableSelectProcess.searchReset()
      this.$forceUpdate()
    },
    searchProcess() {
      this.$refs.tableSelectProcess.queryParam = this.filterFormProcess
      this.$refs.tableSelectProcess.searchQuery(this.filterFormProcess)
    },
    // 工序弹窗事件-----end
    searchResetGoods() {
      this.filterForm.goodsCode = ''
      this.filterForm.goodsName = ''
      this.$refs.tableSelect.searchReset()
    },
    searchGoods() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    // 产品下拉改弹窗
    async openIt() {
      let par = {}
      let res = await APILX.formTypeExtendedFieldList({ formType: 8 })
      if (res.code == 200 && res.result) {
        let formTypeExtendedFields = res.result
        let columnsa = []
        formTypeExtendedFields.forEach((fields) => {
          let tableHead = {
            title: fields.fieldName,
            dataIndex: 'extDataJson.' + fields.fieldKey,
            ellipsis: true,
            width: 150,
            searchIndex: 'extDataJson.' + fields.fieldKey,
            scopedSlots: {
              filterDropdown: 'searchDropdown',
              filterIcon: 'searchIcon'
            }
          }
          columnsa.push(tableHead)
        })
        this.columns = [...this.columns, ...columnsa]
      }
      console.log(this.columns, '列值')
      par = {
        list: '/basicserial/basicSerialInfo/list',
        visible: true, //弹窗开启
        title: '产品', //标题名称
        multi: false, //是否多选
        columns: this.columns, //表格配置
        value: this.buildForm.serialId, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: '物品编号', //回显的中文，如：'张三'
        textKey: 'serialNumber', //回显的中文key
        action: 'post'
      }
      this.$refs.tableSelect.getInit(par)
    },
    getSelectValue(id, text, item) {
      if (item[0].processRouteId) {
        this.craftChange(item[0].processRouteId)
      }
      if (!id) {
        this.serialName = ''
        this.serialNumber = ''
        this.serialSpecifications = ''
        this.buildForm.serialId = ''
        this.goodsName = ''
      }
      this.indexdeta += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      item.length > 0 && this.goodChange(item[0])
      // this.goodChange(item[0])
    },
    outopenIt() {
      let par = {
        list: '/sale/saleOrderInfo/list',
        visible: true, //弹窗开启
        title: '销售订单', //标题名称
        multi: false, //是否多选
        columns: this.outopenItcolumns, //表格配置
        value: this.buildForm.saleOrderId, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: '订单编号', //回显的中文，如：'张三'
        textKey: 'orderCode', //回显的中文key
        action: 'post'
      }
      // console.log( this.outopenItcolumns,' this.outopenItcolumns,')
      this.$refs.SaleSelect.getInit(par)
    },
    getSaleSelectValue(id, text, item) {
      console.log(id, text, item, '列表选择的数据')
      if (!id) {
        this.buildForm.saleOrderId = ''
        this.buildForm.saleCode = ''
        return
      }
      this.Selectindex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.buildForm.saleOrderId = id
      this.buildForm.saleCode = item[0].orderCode
      Qtdl({ orderId: this.buildForm.saleOrderId }).then((res) => {
        if (res.code == 200 && res.result.length == 1) {
          this.goodChange(res.result[0])
        }
      })
    },

    checkInputValue(value) {
      validateDuplicateValue('mess_product_order', 'order_code', value, '', (res) => {
        if (res) {
          this.buildForm.orderCode = ''
          this.$antdMessage.warning(res)
        }
      })
    },
    genEntityCode() {
      API.genEntityCode({ entityCode: 'MESS_PRODUCT_ORDER' }).then((res) => {
        if (res.code == 200) {
          this.buildForm.orderCode = res.result
          this.$refs['ruleFormOne'].validateField(['orderCode'])
        } else {
          this.buildForm.orderCode = ''
          this.$refs['ruleFormOne'].validateField(['orderCode'])
          this.$antdMessage.error(res.message)
        }
      })
    },
    // 计划生产数量变动后重新计算计划投料数量
    resetTotal(value) {
      let list = JSON.parse(JSON.stringify(this.pathParams.dataSource))
      list.forEach((item) => {
        item.processWorkRate = value
      })
      this.pathParams.dataSource = list
    },
    blurNum() {
      console.log(this.buildForm.planProduceNum, '9090')
      if (this.buildForm.planProduceNum == 0) {
        this.buildForm.planProduceNum = ''
      }
    },
    projectBudgetInput(value) {
      this.buildForm.planProduceNum = clearNoNum(value)
      console.log(value, this.buildForm.planProduceNum, '1509')
      this.resetTotal(this.buildForm.planProduceNum)
    },
    processWorkRateInput(value, record) {
      record.processWorkRate = clearNoNum(value)
      this.$forceUpdate()
    },
    // 根据工艺查工序
    craftChange(value) {
      let obj = {
        id: value,
        pageNo: 1,
        pageSize: 999
      }
      this.pathParams.loading = true

      BasicqueryById(obj).then((res) => {
        console.log('222222222', res)
        if (res.success) {
          let items = res.result.basicProcessRouteDetailDtooList || []

          let newData = items.map((e) => {
            if (e.extDataJson) {
              for (let key in e.extDataJson) {
                e[key] = e.extDataJson[key]
                this.$set(e, key, e.extDataJson[key])
              }
            }
            this.$set(e, 'processWorkUnit', this.buildForm.arrPlanTime)
            this.$set(e, 'processWorkRate', this.buildForm.planProduceNum)
            return e
          })

          this.pathParams.dataSource = newData
        } else {
          this.$antdMessage.warning(res.message)
        }
        this.pathParams.loading = false
      })
    },
    // 根据商品查流程，根据流程带出工序
    getGoodsFlow() {
      this.buildForm.craftId = ''
      this.buildForm.craftSource = 'new'
      getAction(`/prodset/messProductFlow/queryFlowListByGoodsId?goodsId=${this.goodsValue}`).then((res) => {
        if (res.result.total && res.result.total === 1) {
          let flowInfo = res.result.records[0]
          this.circuitValue = flowInfo.id
          this.circuitText = flowInfo.flowName
          this.buildForm.craftId = flowInfo.id
          queryFlowProcessListByFlowId({ flowId: flowInfo.id }).then((item) => {
            if (item.result) {
              let newData = item.result.records || []
              this.$refs.craftPath.initialize()
              newData = newData.map((carft) => {
                carft.planStartTime = this.buildForm.planStartTime
                carft.planEndTime = this.buildForm.planEndTime
                return carft
              })
              this.buildForm.craftSource = 'process'
              this.pathParams.dataSource = newData
            }
          })
        }
      })
    },
    goodChange(item) {
      this.buildForm.serialId = item.id
      this.buildForm.serialName = item.serialName
      this.buildForm.serialNumber = item.serialNumber
      this.buildForm.serialSpecifications = item.serialSpecifications
      this.goodsName = `${item.serialNumber || '-'}-${item.serialName || '-'} - ${item.serialSpecifications || '-'}`
    },
    changeStart(v, props) {
      this.$refs.craftPath.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            planStartTime: moment(v).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      ])
    },
    changeEnd(v, props) {
      this.$refs.craftPath.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            planEndTime: moment(v).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      ])
    },
    disabledStartDate(current) {
      const startTime = this.buildForm.arrPlanTime[0]
      const endValue = this.buildForm.arrPlanTime[1]
      if (!current || !endValue) {
        return false
      }
      return startTime.valueOf() > current.valueOf() || current.valueOf() > endValue.valueOf()
    },
    disabledEndDate(current, rowId) {
      let tableValue = this.$refs.craftPath.getValuesSync({ validate: false, rowIds: [rowId] }).values[0]
      const startTime = tableValue.planStartTime ? moment(tableValue.planStartTime, 'YYYY-MM-DD HH:mm') : ''
      const endValue = this.buildForm.arrPlanTime[1]
      if (!current || !endValue) {
        return false
      }
      return startTime.valueOf() > current.valueOf() || current.valueOf() > endValue.valueOf()
    },
    startTimeChange(a, b) {
      console.log(a)
      this.pathParams.dataSource = this.pathParams.dataSource.map((item) => {
        item.processWorkUnit = a
        return item
      })
      console.log(this.pathParams.dataSource, '')
    },
    principalChange(storeVals, row) {
      this.buildForm.principalId = row[0].id
    },
    //页面加载请求数据
    /* 面包屑返回 */
    goBack() {
      this.buildForm = {
        arrPlanTime: '',
        orderCode: '',
        planStartTime: '',
        planEndTime: '',
        planProduceNum: '',
        saleOrderId: '',
        serialId: '',
        produceOrderTaskDtoList: []
      }
      this.jkeForm.visible = false
      this.$emit('refresh')
    },
    // 提交
    submitForm() {
      console.log(this.pathParams.dataSource, 'this.pathParams.dataSource')
      this.$refs.ruleFormOne.validate((valid) => {
        if (valid) {
          this.$refs.createFormItemRef.form.validateFields((err, value) => {
            if (!err) {
              if (this.pathParams.dataSource.length <= 0) {
                this.$antdMessage.warning('请先选择生产任务')
                return
              }
              this.$refs.pathParamsForm.validate((valids) => {
                if (valids) {
                  let param = JSON.parse(JSON.stringify(this.buildForm))
                  param.planStartTime = moment(param.arrPlanTime[0]).format('YYYY-MM-DD HH:mm:ss')
                  param.planEndTime = moment(param.arrPlanTime[1]).format('YYYY-MM-DD HH:mm:ss')

                  let data = this.pathParams.dataSource.map((item, index) => {
                    return {
                      ...item,
                      extDataJson: {},
                      planProduceNum: item.processWorkRate,
                      planStartTime: item.processWorkUnit
                        ? moment(item.processWorkUnit[0]).format('YYYY-MM-DD HH:mm:ss')
                        : '',
                      planEndTime: item.processWorkUnit
                        ? moment(item.processWorkUnit[1]).format('YYYY-MM-DD HH:mm:ss')
                        : '',
                      sort: index,
                      processesId: item.processesId
                    }
                  })
                  console.log(data, '1')

                  data.forEach((item, index) => {
                    for (let key in item) {
                      this.formTypeExtendedFields.forEach((el) => {
                        if (el.fieldKey == key) {
                          if (data[index].extDataJson) {
                            data[index].extDataJson[key] = item[key]
                          } else {
                            data[index].extDataJson = {}
                            data[index].extDataJson[key] = item[key]
                          }
                        }
                      })
                    }
                  })
                  data = data.map((tl) => {
                    delete tl.createBy
                    delete tl.createTime
                    delete tl.updateBy
                    delete tl.updateTime
                    return tl
                  })

                  console.log(data, 'datadatadata')

                  param.produceOrderTaskDtoList = data
                  param.extDataJson = value.extDataJson
                  if (this.buildForm.id) {
                    cardedit(param).then((res) => {
                      if (res.code == 200) {
                        this.$antdMessage.success(res.message)
                        this.jkeForm.visible = false
                        this.$parent.getData()
                      } else {
                        this.$antdMessage.warning(res.message)
                      }
                    })
                  } else {
                    param.produceOrderTaskDtoList = param.produceOrderTaskDtoList.map((tl) => {
                      delete tl.id
                      return tl
                    })
                    carfadd(param).then((res) => {
                      if (res.code == 200) {
                        this.$antdMessage.success(res.message)
                        this.jkeForm.visible = false
                        this.$parent.getData()
                      } else {
                        this.$antdMessage.warning(res.message)
                      }
                    })
                  }
                } else {
                  return false
                }
              })
            } else {
              return false
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style scoped lang='less'>
@import '~@/assets/less/public.less';

.flex(@jc, @ai, @fd: row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}

/deep/ .ant-form-vertical {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;

  .ant-form-item {
    width: 30%;
    padding-bottom: 8px;
    // padding-left: 25px;
  }
}

.form-body {
  height: calc(100vh - 110px);
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.submitBtn {
  .flex(center, center);
  padding: 8px;
}

.flexBox {
  .flex(flex-start, center);
}

// 工艺路线结束
.code-btn {
  position: absolute;
  right: 0;
  top: -50px;
  font-size: 14px;
}

/deep/ .ant-table-column-title {
  display: flex;
  align-items: center;
}
</style>
